package com.ljkj.cordial.chat.presenter;

import android.content.Context;
import android.support.v4.text.PrecomputedTextCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.nic.view.widget.CircleImageView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.rockerhieu.emojicon.EmojiconTextView;

/**
 * 文本
 */
public class TextPresenter extends AChatPresenter {
    public TextPresenter(int direction) {
        super(direction);
//        LayoutInflater.from(view.getContext()).inflate(R.layout.item_chat_right_text, null);
    }

    private Map<Long, String> mSize = new HashMap<>();

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        if (getDirection() == AChatPresenter.LEFT) {
            return new ViewLeftHolder(view);
        }
        return new ViewRightHolder(view);
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position) {
        ChatTableUnit item = (ChatTableUnit) obj;
        Context context = holder.itemView.getContext();
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLeftHolder.ivCorner.getLayoutParams();
            RelativeLayout.LayoutParams paramsMsg = (RelativeLayout.LayoutParams) viewLeftHolder.tvMsgText.getLayoutParams();
            RelativeLayout.LayoutParams paramsDownTime = (RelativeLayout.LayoutParams) viewLeftHolder.tvDownTime.getLayoutParams();
            if (getChatType() == Canstants.SINGLE_CHAT) {
                viewLeftHolder.tvTitle.setVisibility(View.GONE);
                params.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_20);
                viewLeftHolder.ivCorner.setLayoutParams(params);
                paramsMsg.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
                viewLeftHolder.tvMsgText.setLayoutParams(paramsMsg);
                paramsDownTime.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
            } else {
                viewLeftHolder.tvTitle.setVisibility(View.VISIBLE);
                viewLeftHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());
            }

            viewLeftHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewLeftHolder.tvMsgText.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            setVisible(viewLeftHolder.cb, item.isVisible());
            setCheck(viewLeftHolder.cb, item.isChecked());
            loadAvatar(item, viewLeftHolder.ivAvatar);
            setReadFinishState(viewLeftHolder.tvDownTime, item.isStartReadFinish());
            if (isLoadAccess()) {
                leftText(item, viewLeftHolder.tvMsgText);
            } else {
                leftTextDef(item, viewLeftHolder.tvMsgText);
            }
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            viewRightHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewRightHolder.ivFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemReloadClick(v, item, position);
                    }
                }
            });
            viewRightHolder.tvMsgText.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            setVisible(viewRightHolder.cb, item.isVisible());
            if (item.isVisible()) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
            } else {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
            }
            setCheck(viewRightHolder.cb, item.isChecked());

            refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);
            if (isLoadAccess()) {
                leftText(item, viewRightHolder.tvMsgText);
            } else {
                leftTextDef(item, viewRightHolder.tvMsgText);
            }
            loadAvatar(item, viewRightHolder.ivAvatar);
        }
    }


    @Override
    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
        super.bindViewHolder(chatAdapter, position, holder, obj, payLoad);
        ChatTableUnit item = (ChatTableUnit) obj;
        Context context = holder.itemView.getContext();
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type) {
                    loadAvatar(item, viewLeftHolder.ivAvatar);
                }
                if (PayLoad.TEXT == type) {
                    if (isLoadAccess()) {
                        leftText(item, viewLeftHolder.tvMsgText);
                    } else {
                        leftTextDef(item, viewLeftHolder.tvMsgText);
                    }

                }
                if (PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewLeftHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.VISIBLE == type || PayLoad.INVISIBLE == type) {
                    setVisible(viewLeftHolder.cb, item.isVisible());
                }
                if (PayLoad.SELECTED == type || PayLoad.UNSELECT == type) {
                    setCheck(viewLeftHolder.cb, item.isChecked());
                }

            }
            viewLeftHolder.ivIsVisitor.setVisibility(IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType()) ? View.VISIBLE : View.GONE);
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type) {
                    loadAvatar(item, viewRightHolder.ivAvatar);
                }
                if (PayLoad.TEXT == type) {
                    if (isLoadAccess()) {
                        leftText(item, viewRightHolder.tvMsgText);
                    } else {
                        leftTextDef(item, viewRightHolder.tvMsgText);
                    }

                }
                if (PayLoad.DOWN_TIME == type && item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                    if (item.isStartReadFinish()) {
                        viewRightHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.REQ_STATE == type) {
                    refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);
                }
                if (PayLoad.VISIBLE == type || PayLoad.INVISIBLE == type) {
                    setVisible(viewRightHolder.cb, item.isVisible());
                    if (item.isVisible()) {
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                        params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                        params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
                    } else {
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                        params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
                    }
                }
                if (PayLoad.SELECTED == type || PayLoad.UNSELECT == type) {
                    setCheck(viewRightHolder.cb, item.isChecked());
                }
            }
        }


    }

    private String getEmptyText(String text) {
        if (TextUtils.isEmpty(text)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            sb.append(" ");
        }
        return sb.toString();
    }

    private void leftTextDef(ChatTableUnit item, EmojiconTextView tvMsgText) {
//        getEmptyText(item.getTextMsg())
        tvMsgText.setText("");
        if (mSize.containsKey(item.getId())) {
            String size = mSize.get(item.getId());
            int w = Integer.valueOf(size.split(",")[0]);
            int h = Integer.valueOf(size.split(",")[1]);
            tvMsgText.getLayoutParams().width = w;
            tvMsgText.getLayoutParams().height = h;
        }
    }

    private void leftText(ChatTableUnit item, EmojiconTextView tvMsgText) {
//        try {
        if (item.getTextMsg().length() < 200) {
            tvMsgText.setText(item.getTextMsg());
        } else {
            tvMsgText.setTextFuture(PrecomputedTextCompat.getTextFuture(item.getTextMsg(), tvMsgText.getTextMetricsParamsCompat(), null));
        }
        mSize.put(item.getId(), tvMsgText.getLayoutParams().width + "," + tvMsgText.getLayoutParams().height);
//            if (item.getCharSequenceText() != null) {
//                CharSequence text = item.getCharSequenceText().getSequence();
//                if (TextUtils.isEmpty(text)) {
//                    return;
//                }
//                int maxWidth = tvMsgText.getResources().getDisplayMetrics().widthPixels / 2;
//                if (EmojiPackage.getWidth(text.toString()) > maxWidth) {
//                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvMsgText.getLayoutParams();
//                    params.width = maxWidth;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        EmojiPackage.handlerTextThread(context, item.getTextMsg(), new EmojiPackage.OnHandlerThreadListener() {
//            @Override
//            public void deCodeMsg(CharSequence text) {
//                tvMsgText.setText(text);
//                int maxWidth = tvMsgText.getResources().getDisplayMetrics().widthPixels / 2;
//                if (EmojiPackage.getWidth(item.getTextMsg()) > maxWidth) {
//                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvMsgText.getLayoutParams();
//                    params.width = maxWidth;
//                }
////                map.put(item.getId(), text);
//            }
//        });

    }

    public static class ViewLeftHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.ll_avatar)
        FrameLayout llAvatar;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_msg_text)
        EmojiconTextView tvMsgText;
        @BindView(R.id.iv_msg_corner)
        ImageView ivCorner;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewLeftHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
//            setIsRecyclable(false);
        }
    }

    public static class ViewRightHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.tv_msg_text)
        EmojiconTextView tvMsgText;
        @BindView(R.id.iv_fail)
        ImageView ivFail;
        @BindView(R.id.iv_msg_corner)
        ImageView ivCorner;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewRightHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

}
